import React, { Component } from 'react';
import {
  Table,
  Select,
  Input,
  Button,
  Dropdown,
  Menu,
  Message,
  Pagination,
  Tooltip,
} from '@knownsec/react-component';
import { Link, withRouter } from 'react-router-dom';
import { getScanResult, getGroupResult, eventBatch } from '~/API';
import moment from 'moment';
import { filterNull } from '@/utils';
import RuleTable from '@/components/RuleTable';

import editeIcon from '@/assets/svg/bianji.svg';
import s from './style.module.less';
import { securityNameMap, outLinkOption, actionDict } from '../columns';
import CopyText from '@/components/copy';
import EmptyData from '../../../../components/EmptyData';

const info = localStorage.info ? JSON.parse(localStorage.info).modules : [];
const outLinkDict = {};
for (const item of outLinkOption) {
  outLinkDict[item.value] = item.label;
}

class ChangeCheck extends Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        key: 'target_url',
        dataIndex: 'target_url',
        title: '风险地址',
        render: (value, _data) => {
          const name = _data?.detail?.url || '-';
          return (
            <Tooltip
              overlay={
                <>
                  <p>
                    <CopyText text={name} />
                  </p>
                </>
              }
              placement="topLeft"
            >
              <div className={s.textellipsis}>{name}</div>
            </Tooltip>
          );
        },
      },
      {
        key: 'text_result',
        dataIndex: 'text_result',
        title: '内容变更',
        className: 'stablewidth',
        sorter: true,
        render: (e, row) => {
          const change_ratio = row.detail.text_result?.change_ratio;
          const is_checked =  row.detail.text_result?.is_checked
          return (
            this.columnStatus(change_ratio,is_checked)
          );
        },
      },
      {
        key: 'structure_result',
        dataIndex: 'structure_result',
        title: '结构变更',
        className: 'stablewidth',
        sorter: true,
        render: (e, row) => {
          const change_ratio = row.detail?.structure_result?.change_ratio;
          const is_checked =  row.detail.structure_result?.is_checked
          return (
            this.columnStatus(change_ratio,is_checked)
          );
        },
      },
      {
        key: 'resource_result',
        dataIndex: 'resource_result',
        title: '资源变更',
        sorter: true,
        className: 'stablewidth',
        render: (e, row) => {
          const change_ratio = row.detail?.resource_result?.change_ratio;
          const is_checked =  row.detail.resource_result?.is_checked
          return (
            this.columnStatus(change_ratio,is_checked)
          );
        },
      },
      {
        key: 'found_at',
        dataIndex: 'found_at',
        title: '发现时间',
        className: 'stablewidthxl',
        render: (value, data) =>
          data.detail?.found_at
            ? moment(data.detail.found_at).format('YYYY-MM-DD HH:mm:ss')
            : moment(data.created_at).format('YYYY-MM-DD HH:mm:ss') || '-',
      },
      {
        key: 'type',
        dataIndex: 'type',
        title: '状态',
        className: 'stablewidth',
        render: (value, data) => (
          <Dropdown overlay={this.menu([data.id])} placement="bottomCenter" arrow>
            <span>
              {actionDict[data?.action?.action] || '待修复'}{' '}
              <img className={s.eidte} src={editeIcon} alt="" />
            </span>
          </Dropdown>
        ),
      },
      {
        key: 'option',
        dataIndex: 'option',
        title: '操作',
        className: 'stablewidth',
        render: (value, _data) => (
          <>
            <Link
              className={s.linkStyle}
              to={{
                pathname: `/change_detail/`,
                search: `id=${_data.id}&tid=${this.props.targetId}&type=change_check&sid=${
                  this.props.sid || ''
                }&back=${encodeURI(this.state.backUrl)}&rowSid=${_data.task_session_id}`,
              }}
            >
              查看
            </Link>
          </>
        ),
      },
    ];
    const prefilter = new URLSearchParams(props.location.search).get('filter');
    const filter = prefilter ? JSON.parse(prefilter) || {} : {};
    const securityQuery = filter.sq || {};
    this.state = {
      selectIds: [],
      refe: false,
      loading: false,
      task_type: [],
      status: [],
      disk_url: '',
      datalist: [],
      page: securityQuery.page || 1,
      limit: securityQuery.limit || 10,
      total: 0,
      severity_name: securityQuery.severity_name || '',
      action: securityQuery.action || '',
      risk_url: securityQuery.risk_url || '',
      backUrl: '',
      sort_by: '',
      sort_order: '',
    };
  }
  componentDidUpdate(prevProps) {
    if (prevProps.sid && prevProps.sid != this.props.sid) {
      this.getData();
    }
  }
  componentDidMount() {
    this.getData();
  }
  columnStatus(change_ratio,is_checked){
    if(is_checked){
      if(change_ratio){
        return (change_ratio * 100).toFixed(2) + '%'
      }else{
        return (<Tooltip
          overlay={
              <p>
                监测结果未变更或者低于设置的变更比例
              </p>
          }
          placement="topLeft"
        >
          <div className={s.textellipsis}>- -</div>
        </Tooltip>)
      }
    }else{
      return (<Tooltip
        overlay={
            <p>
              未开启监测
            </p>
        }
        placement="topLeft"
      >
        <div className={s.textellipsis}>- -</div>
      </Tooltip>)
    }
  }
  menu(ids) {
    return (
      <Menu>
        <Menu.Item onClick={() => this.fixStatus({ action: 0 }, ids)}>
          <span>待修复</span>
        </Menu.Item>
        <Menu.Item onClick={() => this.fixStatus({ action: 1 }, ids)}>
          <span>已修复</span>
        </Menu.Item>
        <Menu.Item onClick={() => this.fixStatus({ action: 2 }, ids)}>
          <span>忽略</span>
        </Menu.Item>
      </Menu>
    );
  }
  fixStatus(params, ids) {
    var _this = this;
    const data = Object.assign({ event_ids: ids || this.state.selectIds }, params);
    eventBatch(data).then((res) => {
      if (res.status === 'success') {
        _this.getData();
        _this.setState({ refe: !_this.state.refe, selectIds: [] });
        Message.show({
          pro: true,
          type: 'success',
          message: '操作成功',
          showClose: false,
        });
      }
    });
  }
  onSearchChange = (page) => {
    var _this = this;
    if (page.page) {
      _this.setState(
        {
          page: page.page,
          limit: page.limit,
        },
        function () {
          _this.getData();
        }
      );
    } else {
      _this.setState(
        {
          page: 1,
          limit: 10,
        },
        function () {
          _this.getData();
        }
      );
    }
  };
  getData() {
    if (this.props?.fetchable === 'fail') return false;
    const querydata = {
      page: this.state.page,
      limit: this.state.limit,
      severity_name: this.state.severity_name,
      action: this.state.action,
      risk_url: this.state.risk_url,
      sort_by: this.state.sort_by,
      sort_order: this.state.sort_order,
    };
    const f = JSON.stringify(filterNull({ locKeyNum: '篡改', sq: querydata }));
    this.setState({ backUrl: f, selectIds: [], refe: !this.state.refe });
    this.props.history.replace(
      `/dashboard/?id=${this.props.targetId}&type=${this.props.type || ''}&sid=${
        this.props.sid || ''
      }&filter=${encodeURI(f)}`
    );
    let API = null;
    if (this.props.sid) {
      API = getGroupResult({ id: this.props.sid, data: filterNull(querydata) });
    } else {
      API = getScanResult({
        id: this.props.targetId,
        type: 'change_check',
        data: filterNull(querydata),
      });
    }
    this.setState({ loading: true });
    API.then((res) => {
      if (res.status === 'success') {
        const data = res.data?.data.events;
        data.map((item) => {
          item.id = item.event_id;
          item.key = item.event_id;
        });
        this.setState({ datalist: data, total: res.data.total, loading: false });
      } else {
        this.setState({ datalist: [], total: 0, loading: false });
      }
    }).catch((_) => {
      this.setState({ datalist: [], total: 0, loading: false });
    });
  }
  setVal(label, val, type) {
    let callback, obj;
    obj = { [label]: val };
    if (type) {
      obj = { [label]: val, page: 1, limit: 10 };
      callback = function () {
        this.getData();
      };
    }
    this.setState(obj, callback);
  }
  setSelTable(e) {
    this.setVal('selectIds', e);
  }
  generateOption(arr) {
    let res = arr
      .map((item, index) => {
        return { label: item, value: index };
      })
      .filter((v) => v.label);
    return res;
  }
  renderSearch() {
    return (
      <>
        <Select
          option={this.generateOption(actionDict)}
          pro
          placeholder="请选择篡改状态"
          className="selectItem"
          clearable
          value={this.state.action}
          onChange={({ selectedItem }) => {
            const params = selectedItem[0] ? selectedItem[0].value : '';
            this.setVal('action', [params], 'getData');
          }}
        />
        <Input
          pro
          placeholder="搜索风险地址"
          value={this.state.risk_url}
          autoComplete={'off'}
          search
          className="search-button last"
          onSearch={this.onSearchChange}
          clear
          onChange={(value) => {
            this.setVal('risk_url', value.value);
            if (!value.e) {
              this.onSearchChange({ val: 'risk_url' });
            }
          }}
        ></Input>
      </>
    );
  }
  render() {
    const this_ = this;
    return (
      <div className={s.wangsecurity}>
        <div className="searchBox">
          <div className={s.searchLeft}>
            <Dropdown
              disabled={!this.state.selectIds.length}
              overlay={this.menu(this.state.selectIds)}
              placement="bottomCenter"
              arrow
            >
              <Button pro type="default">
                批量操作
              </Button>
            </Dropdown>
          </div>
          <div className="searchRight">{this.renderSearch()}</div>
        </div>
        {info.includes('change_check') ? (
          <Table
            selectable
            refre={this.state.refe}
            loading={this.state.loading}
            pro
            showSorterTooltip={false}
            empty={this.props?.fetchable === 'fail' && <EmptyData text="未开启该监测项" />}
            columns={this.columns}
            data={this.state.datalist}
            onChange={(pagination, filters, sorter) => {
              const obj = { ascend: 1, descend: -1 };
              this.setState({ sort_by: obj[sorter.order]&&sorter.field, sort_order: obj[sorter.order] }, () => {
                this.getData();
              });
              console.log('[  ]-355', sorter);
            }}
            rowSelection={{
              ...{
                onChange: (e) => {
                  this_.setState({ selectIds: e });
                },
              },
            }}
          ></Table>
        ) : (
          <RuleTable
            selectable
            className={this.state.selectIds.length ? 'half-select' : ''}
            columns={this.columns}
            data={this.state.datalist}
          ></RuleTable>
        )}
        {info.includes('change_check') && this.state.total > 10 && (
          <Pagination
            className={s.pagination}
            current={this.state.page}
            showQuickJumper={{ goButton: true }}
            showSizeChanger={true}
            pageSize={this.state.limit}
            pageSizeOptions={['10', '20', '50']}
            showTotal={(total) => `共${total}条`}
            total={this.state.total}
            onChange={(page, size) => {
              this.onSearchChange({ page, limit: size });
            }}
          />
        )}
      </div>
    );
  }
}

export default withRouter(ChangeCheck);
